package com.leyou.controller;

import com.leyou.api.ActivityService;
import com.leyou.api.ReceiveService;
import com.leyou.api.TableService;
import com.leyou.constant.DefineException;
import com.leyou.constant.ResponseMessage;
import com.leyou.constant.Result;
import com.leyou.domain.db1entity.ConditionAndGoods;
import com.leyou.domain.db1entity.Couponandactivity;
import com.leyou.domain.db1entity.TableCell;
import com.leyou.domain.db1entity.TurnTableActivity;
import com.leyou.domain.vo.ConditionPutVO;
import com.leyou.domain.vo.RecordPageVO;
import com.leyou.domain.vo.ShowVO;
import com.leyou.domain.vo.TablePutVO;
import com.leyou.utils.Utils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author lixin
 * @Date 2018/11/13 15:33
 * @Version 1.0
 * @Description TODO
 **/
@RequestMapping("table")
@RestController
public class TableController {


    @Autowired
    TableService tableService;

    @Autowired
    ActivityService activityService;

    @Autowired
    ReceiveService receiveService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @PostMapping("putActivity")
    public ResponseMessage putActivity(@RequestBody TablePutVO tablePutVO, BindingResult result, @CookieValue(name = "ticket") String ticket) {

        StringBuilder sb = new StringBuilder();
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                sb.append(error.getDefaultMessage());
            }
            return Result.error(900008, "信息如下" + sb.toString());
        }
        if (Utils.isNull(tablePutVO.getBegintime(), tablePutVO.getEndtime())) {
            return Result.error(900008, "开始时间和结束时间不能为空");
        } else {
            if (tablePutVO.getBegintime().compareTo(tablePutVO.getEndtime()) >= 0) {
                return Result.error(400012, "活动结束时间需要大于开始时间");
            }
        }

        //转盘条件验证
        if (StringUtils.isBlank(tablePutVO.getConditionPutVO().getConditiontype())) {
            return Result.error(400000, "转盘条件类型不能为空condition_type");
        }

        switch (tablePutVO.getConditionPutVO().getConditiontype()) {
            case "0":
                break;
            case "1":
                if (tablePutVO.getConditionPutVO().getPoints() == null) {
                    return Result.error(400000, "条件积分数不能为空points");
                }
                break;
            case "2":
                if (tablePutVO.getConditionPutVO().getConditionAndGoodsList() == null
                        || tablePutVO.getConditionPutVO().getConditionAndGoodsList().size() == 0) {
                    return Result.error(400000, "条件类型为2则物品主键列表不能为空condition_good_list");
                }
                if (!receiveService.checkSkuList(tablePutVO.getConditionPutVO().getConditionAndGoodsList())) {
                    return Result.error(400000, "存在无效SKU");
                }
                break;
            default:
                return Result.error(400000, "条件类型只能为0或1或2");
        }


        try {
            tablePutVO.setUsername(activityService.getManagerByTicket(ticket).getManagername());
            tableService.putActivity(tablePutVO);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(400000, e.getMessage());
        }

        return Result.success(200000, "添加成功");
    }


    @PostMapping("getTableActivityList")
    public ResponseMessage getTableActivityList(@RequestParam(name = "page_num", required = false) Integer pageNum,
                                                @RequestParam(name = "page_size", required = false) Integer pageSize) {

        if (Utils.isNull(pageNum, pageSize)) {
            return Result.success(200000, "成功", tableService.getTableActivityList(1, 5));
        } else {
            return Result.success(200000, "成功", tableService.getTableActivityList(pageNum, pageSize));
        }
    }


    @PostMapping("putActivityCell")
    public ResponseMessage putActivityCell(@RequestBody @Validated TableCell tableCell, BindingResult result) {

        StringBuilder sb = new StringBuilder();
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                sb.append(error.getDefaultMessage());
            }
            return Result.error(900009, sb.toString());
        }
        if (!"4".equals(tableCell.getCelltype())) {
            tableCell.setCount(tableCell.getTotal());
        }


        //验证奖品号
        if (tableCell.getPrizeorder() <= 0 || tableCell.getPrizeorder() > 9) {
            return Result.error(400000, "奖品类型只能在1-9之间");
        }

        //验证序号重复性
        try {
            tableService.checkPrizeOrder(tableCell);
        } catch (Exception e) {
            return Result.error(40000, e.getMessage());
        }


        List<Couponandactivity> couponandactivityList = new ArrayList<>();

        switch (tableCell.getCelltype()) {
            case "1":
                //优惠券
                //券号、额度、数量
                if (StringUtils.isBlank(tableCell.getCouponkey())) {
                    return Result.error(400000, "券号不能为空");
                }
                if (tableCell.getQuota() == null || tableCell.getTotal() == null) {
                    return Result.error(400000, "额度和数量不能为空");
                }
                //验证有效性
                couponandactivityList.add(new Couponandactivity(tableCell.getCouponkey()));
                try {
                    activityService.checkCoupon(couponandactivityList);
                } catch (DefineException e) {
                    return Result.error(e.getErrorCode(), e.getMessage());
                }
                break;
            case "2":
                //积分
                //数量
                if (tableCell.getTotal() == null) {
                    return Result.error(400000, "积分数不能为空");
                }
                break;
            case "3":
                //实物
                //实物名称
                tableCell.setQuota(1);
                if (StringUtils.isBlank(tableCell.getGoodsname())) {
                    return Result.error(400000, "实物名称不能为空");
                }
                break;
            case "4":
                //谢谢惠顾
                tableCell.setTotal(0);
                break;
            default:
                return Result.error(400000, "格子类型只能1234");
        }


        try {
            tableService.putTableCell(tableCell);
        } catch (DefineException e) {
            return Result.error(e.getErrorCode(), e.getMessage());
        }
        return Result.success(200000, "添加成功");
    }


    @PostMapping("getTableById")
    public ResponseMessage getTableById(@RequestBody TurnTableActivity turnTableActivity) {
        return Result.success(tableService.getTableById(turnTableActivity.getActivitykey()));
    }

    @PostMapping("updateTableById")
    public ResponseMessage updateTableById(@RequestBody TurnTableActivity turnTableActivity) {
        try {
            tableService.updateTableById(turnTableActivity);
        } catch (DefineException e) {
            return Result.error(e.getErrorCode(), e.getMessage());
        }
        return Result.success(200000, "修改成功");
    }

    @PostMapping("getTableCellList/{activity}")
    ResponseMessage getTableCellList(@PathVariable("activity") String activity) {

        if (StringUtils.isBlank(activity)) {
            return Result.error(400000, "活动主键为空");
        }
        return Result.success(tableService.getTableCellList(activity));
    }

    @PostMapping("deleteCell")
    ResponseMessage deleteCell(@RequestBody TableCell tableCell) {

        if (StringUtils.isBlank(tableCell.getCellkey())) {
            return Result.error(400000, "必要参数为空");
        }

        try {
            tableService.deleteCell(tableCell);
        } catch (Exception e) {
            return Result.error(400000, e.getMessage());
        }
        return Result.success(200000, "操作成功");
    }


    @PostMapping("activityShow")
    ResponseMessage activityShow() {

        Map<String, Object> map = tableService.activityShow();

        List<ShowVO> activityShow = (List<ShowVO>) map.get("activityShow");

        List<ShowVO> recordShow = (List<ShowVO>) map.get("recordShow");

        int[] activityArr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        int[] recordArr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        int[] avgArr = new int[12];

        for (ShowVO showVO : activityShow) {
            activityArr[showVO.getMonth() - 1] = showVO.getValue();
        }

        for (ShowVO showVO : recordShow) {
            recordArr[showVO.getMonth() - 1] = showVO.getValue();
        }

        for (int i = 0; i < activityArr.length; i++) {

            if (activityArr[i] != 0) {
                avgArr[i] = recordArr[i] / activityArr[i];
            }
        }

        Object[] arr = {activityArr, recordArr, avgArr};
        return Result.success(arr);
    }

    @PostMapping("getActivityRecord")
    ResponseMessage getActivityRecord(@RequestBody RecordPageVO recordPageVO) {

        if (StringUtils.isBlank(recordPageVO.getActivitykey())) {
            return Result.error(400000, "必要参数为空");
        }
        if (recordPageVO.getPageNum() == null) {
            recordPageVO.setPageNum(1);
            recordPageVO.setPageSize(5);
        }

        return Result.success(tableService.getTurnTableRecord(recordPageVO));
    }


    @PostMapping("uploadTurn")
    ResponseMessage uploadTurn(@RequestParam("file") MultipartFile file) {


        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String line = "";
        List<String> dataList = new ArrayList<String>();
        try {
            inputStream = file.getInputStream();
            InputStreamReader is = new InputStreamReader(inputStream, "gbk");
            bufferedReader = new BufferedReader(is);
            while ((line = bufferedReader.readLine()) != null) {
                dataList.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(400000, "文件解析失败");
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                    bufferedReader = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (dataList.size() != 2) {
            return Result.error(400000, "格式不正确");
        }
        String[] list = dataList.get(1).split(",");

        if (list.length != 14) {
            return Result.error(400000, "格式不正确");
        }

        TablePutVO tablePutVO = new TablePutVO();
        tablePutVO.setTheme(list[0]);
        tablePutVO.setSharurl(list[1]);
        tablePutVO.setBackgroundurl(list[2]);
        tablePutVO.setTurntableurl(list[3]);
        tablePutVO.setPointerurl(list[4]);

        Date begintime = null;
        Date endtime = null;
        try {
            String beginStr = list[5].replace("/", "-");
            String endStr = list[6].replace("/", "-");
            begintime = Date.valueOf(beginStr);
            endtime = Date.valueOf(endStr);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(40000, e.getMessage());
        }

        if (begintime.compareTo(endtime) > 0) {
            return Result.error(400000, "开始时间应小于结束时间");
        }
        tablePutVO.setBegintime(begintime);
        tablePutVO.setEndtime(endtime);

        ConditionPutVO conditionPutVO = new ConditionPutVO();
        conditionPutVO.setConditiontype(list[8]);
        switch (list[8]) {
            case "0":
                break;
            case "1":
                try {
                    conditionPutVO.setPoints(Integer.valueOf(list[10]));
                } catch (Exception e) {
                    return Result.error(400000, "积分数数据异常");
                }
                break;

            case "2":
                String[] strings = list[10].split("-");
                try {
                    Date buyBegintime = Date.valueOf(list[12].replace("/", "-"));
                    Date buyEndtime = Date.valueOf(list[13].replace("/", "-"));
                    List<ConditionAndGoods> conditionAndGoodsList = new ArrayList<>();
                    for (int i = 0; i < strings.length; i++) {
                        ConditionAndGoods conditionAndGoods = new ConditionAndGoods();
                        conditionAndGoods.setBegintime(buyBegintime);
                        conditionAndGoods.setEndtime(buyEndtime);
                        conditionAndGoods.setGoodskey(strings[i]);
                        conditionAndGoodsList.add(conditionAndGoods);
                    }
                    conditionPutVO.setConditionAndGoodsList(conditionAndGoodsList);
                    conditionPutVO.setQuoation(Integer.valueOf(list[14]));
                    if (!receiveService.checkSkuList(conditionAndGoodsList)) {
                        return Result.error(400000, "存在无效SKU");
                    }
                } catch (Exception e) {
                    return Result.error(400000, e.getMessage());
                }
                break;
            default:
                return Result.error(400000, "条件类型出错");
        }

        tablePutVO.setConditionPutVO(conditionPutVO);
        try {
            tableService.putActivity(tablePutVO);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(400000, e.getMessage());
        }
        return Result.success();
    }
}

